package com.sfh.sfhshopweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfh.sfhshopweb.entity.ToolsFile;
import com.sfh.sfhshopweb.mapper.ToolsFileMapper;
import com.sfh.sfhshopweb.service.IToolsFileService;
import com.sfh.sfhshopweb.utils.CosUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.List;

@Slf4j
@Service
public class ToolsFileServiceImpl extends ServiceImpl<ToolsFileMapper, ToolsFile> implements IToolsFileService {


    @Autowired
    private ToolsFileMapper toolsFileMapper;

    @Override
    public ToolsFile uploadFile(MultipartFile file, String modelCode, String busikey) {
        String fileName = file.getOriginalFilename();
        long fileSize = file.getSize();
        try {
            String filePath = modelCode + "/" + busikey + "-" + fileName;
            // 获取文件类型
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            URL url = CosUtils.uploadFile(file, filePath);
            log.info("上传成功，url:{}", url);

            URL encodeUrl = CosUtils.getEncodeUrl(filePath);

            ToolsFile toolsFile = new ToolsFile();
            toolsFile.setFileName(fileName);
            toolsFile.setFileSize(fileSize);
            toolsFile.setFilePath(filePath);
            toolsFile.setModelCode(modelCode);
            toolsFile.setBusiKey(busikey);
            toolsFile.setFileType(fileType);
            toolsFile.setUrl(encodeUrl.toString());
            toolsFile.setPreviewUrl(CosUtils.getPreviewUrl(filePath).toString());
            toolsFile.insert();

            return toolsFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<ToolsFile> queryFile(String modelCode, String busiKey) {
        QueryWrapper<ToolsFile> wrapper = new QueryWrapper<>();
        wrapper.eq("model_code", modelCode);
        wrapper.eq("busi_key", busiKey);
        List<ToolsFile> toolsFiles = toolsFileMapper.selectList(wrapper);
        toolsFiles.forEach(each -> {
            each.setUrl(CosUtils.getEncodeUrl(each.getFilePath()).toString());
            each.setPreviewUrl(CosUtils.getPreviewUrl(each.getFilePath()).toString());
        });
        return toolsFiles;
    }

    @Override
    @Transactional
    public boolean removeFile(String id) {
        ToolsFile toolsFile = toolsFileMapper.selectById(id);
        Boolean b = CosUtils.removeFile(toolsFile.getFilePath());
        int i = toolsFileMapper.deleteById(id);
        return b && i > 0;
    }
}
